#! /usr/bin/env python

import roslib; roslib.load_manifest('storage')
import rospy
import sqlite3
import actionlib
import std_msgs
from storage.msg import *

def addPerson(target):
	conn2 = sqlite3.connect('../ros_workspace/storage/storageDB')
	c2 = conn2.cursor()
	img=(target[0],target[1])
	c2.execute('insert into images values (NULL,?,?)', img)
	imageID=c2.lastrowid
	for i in range(int(target[2])):
		person=(imageID,i,target[3+i*2],target[4+i*2])
		c2.execute('insert into peopleInstances values (NULL,?,?,null,null,?,?)',person)
	conn2.commit()
	c2.close()
	pub = rospy.Publisher("androidFace",androidCall,latch=True)
	pub.publish(android([2]),target[1]))
	rospy.loginfo("this happened")

def updateEyeDist(target):
	rospy.loginfo("updating eyedist")
	conn3 = sqlite3.connect('../ros_workspace/storage/storageDB')
	c3 = conn3.cursor()
	eyeList=(target[2],target[0],target[1])
	rospy.loginfo("start")
	c3.execute('update peopleInstances set eyeDistance = ? where imageID = ? and faceNumber = ?',eyeList)
	rospy.loginfo("end")
	conn3.commit()
	c3.close() 

class storageServer:
  def __init__(self):
    self.server = actionlib.SimpleActionServer("addPerson", addPersonAction, self.execute, False)
    self.server.start()

  def execute(self,goal):
    addPerson(goal.target)
    #once we have reached our target we tell the client that we succeeded
    self.server.set_succeeded()
    
class eyeDistServer:
  def __init__(self):
	  self.eyeServer = actionlib.SimpleActionServer("eyeDist", eyeDistAction, self.execute, False)
	  self.eyeServer.start()
	  
  def execute(self,goal):
	  updateEyeDist(goal.target)
	  self.eyeServer.set_succeeded()
if __name__ == '__main__':
	#NOTE: Gotta Make the node executable : chmod +x nodes/storageServer.py
	rospy.init_node("storageServer")
	
	conn = sqlite3.connect('../ros_workspace/storage/storageDB')
	c = conn.cursor()

	# Create table
	c.execute("""create table if not exists peopleInstances(faceID integer primary key autoincrement, imageID integer,faceNumber integer,name string, eyeDistance real, height real,shirtColor string)""")
	c.execute("""create table if not exists peopleDictionary(name string, eyeDistance real,  height real, shirtColor string)""")
	c.execute("""create table if not exists images(imageID integer primary key autoincrement, url string, facesPath string)""")
	# Save (commit) the changes
	conn.commit()
	c.close()
	eyeServer=eyeDistServer()
	server=storageServer()
	rospy.spin()
